<template>
  <!-- 上传文件 -->
  <div class="upload-file-container">
    <el-upload
        ref="uploadFile"
        action="/adminapi/common/upload/file"
        drag
        multiple
        name="file"
        :file-list="fileList"
        :limit="limit"
        :on-success="handleAvatarSuccess"
        :on-remove="handleAcatarRemove"
        :on-change="uploadFileChange"
        :headers="{'authentication': loginToken, 'x-header-client': 'WLTX-ADMIN-API'}">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" style="color: red;" v-if="uploadTip" slot="tip">{{ uploadTip }}</div>
      </el-upload>
  </div>
</template>
<script>
import $storage from '@/utils/storage.js'

export default {
  name: 'UploadFile',
  props: {
    limit: {
      type: Number,
      default: ()=> 1
    },
    uploadValue: {
      type: Array,
      default: ()=> []
    },
    uploadTip: {
      type: String,
      default: ()=> null
    }
  },
  computed: {
    fileList: {
      get() {
        let showFiles = []
        this.uploadValue.forEach(item=> {
          if(item) {
            showFiles.push({ url: item, name: item.substring(item.lastIndexOf('/')+1, item.length)})
          }
        })
        return showFiles
      }
    }
  },
  data() {
    return {
      loginToken: $storage.getUserToken()
    }
  },
  methods: {
    // 选择文件上传成功
    async handleAvatarSuccess(res){
      if(!res.data) this.$message.error('上传失败')
      let showImageList = this.uploadValue
      showImageList.push(res.data.url)
      this.$emit('update:uploadValue', showImageList)
      this.uploadChange()
    },

    async handleAcatarRemove(file, fileList){
      let showImageList = []
      fileList.forEach(item=> {
        showImageList.push(item.url)
      })
      this.$emit('update:uploadValue', showImageList)
      this.uploadChange()
    },

    async uploadFileChange(file) {
      this.$emit('update:uploadSize', Math.floor(file.size / 1024 /1024))
    },

    // 添加change事件
    async uploadChange(){
      this.$emit('uploadChange')
    }
  }
}
</script>
<style lang="scss" scoped>
  .upload-file-container {
    width: 100%;

    ::v-deep .el-upload--text {
      width: 100% !important;

      .el-upload-dragger {
        width: 100% !important;
      }
    }
  }
</style>